<template>
  <PageWrapper v-loading="loading" loading-tip="加载中...">
    <div class="p-4 p-4-tag">
      <div class="tag" ref="divDom">
        <div class="main-head">
          <a-input-search
            class="margin5"
            v-model:value="searchDriver"
            placeholder="搜索"
            :allowClear="true"
            style="width: 237px"
            @search="onSearchDriver"
          />
          <a-button
            type="primary"
            class="margin5"
            @click="handleAddFather"
            v-if="hasPermission('2-1-addFather')"
            >创 建</a-button
          >
          <a-button
            type="primary"
            class="margin5"
            @click="handleAddChild"
            v-if="hasPermission('2-1-addChild')"
            >创 建 子</a-button
          >
          <a-button
            type="primary"
            class="margin5"
            @click="handleSave"
            v-if="hasPermission('2-1-save')"
            >保 存</a-button
          >
          <a-button class="margin5" @click="handleDel" v-if="hasPermission('2-1-del')"
            >删除</a-button
          >
        </div>
        <div class="main-nav">
          <div class="btns">
            <a-button class="btns-item" @click="expandAll(true)">展开全部</a-button>
            <a-button class="btns-item" @click="expandAll(false)">折叠全部</a-button>
          </div>
          <BasicTree
            title=""
            ref="treeRef"
            :treeData="treeDataPro"
            :fieldNames="{ key: 'Key', title: 'Name', children: 'Children' }"
            :onSelect="handleTreeSelect"
          />
        </div>
        <div class="main-content">
          <BasicForm @register="registerForm" />
        </div>
      </div>
    </div>
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { PageWrapper } from '/@/components/Page';
  import { BasicTree, TreeActionType } from '/@/components/Tree/index';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { ref, unref, nextTick, onMounted } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { cloneDeep } from 'lodash-es';

  import {
    getenterprisetree,
    getenterprise,
    updateenterprise,
    addenterprise,
    delenterprise,
  } from '/@/api/enterprise/index';

  let searchDriver = ref('');
  const { hasPermission } = usePermission();
  let loading = ref(false);
  // 当前id
  let currentInfo = {};
  // 父级信息
  let parentInfo = {};
  // 默认层级
  let defaultOptions = [
    { label: '集团', value: '1' },
    { label: '公司', value: '2' },
    { label: '工厂', value: '3' },
    { label: '车间', value: '4' },
    { label: '产线', value: '5' },
  ];
  const treeRef = ref<Nullable<TreeActionType>>(null);
  let treeDataPro: any = ref([]);
  // 表单内容
  const schemas: FormSchema[] = [
    {
      field: 'Name',
      component: 'Input',
      label: '名称：',
      colProps: {
        span: 8,
      },
      componentProps: {
        style: {
          width: '80%',
        },
      },
      rules: [
        {
          required: true,
          message: '请输入名称',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'Code',
      component: 'Input',
      label: '编码：',
      colProps: {
        span: 8,
      },
      componentProps: {
        style: {
          width: '80%',
        },
      },
      rules: [
        {
          required: true,
          message: '请输入编码',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'ParentName',
      component: 'Input',
      label: '父模型：',
      colProps: {
        span: 8,
      },
      componentProps: {
        disabled: true,
        style: {
          width: '80%',
        },
      },
    },
    {
      field: 'Level',
      component: 'Select',
      label: '企业层级：',
      colProps: {
        span: 8,
      },
      componentProps: {
        style: {
          width: '80%',
        },
        placeholder: '请选择企业层级',
        options: defaultOptions,
      },
      rules: [
        {
          required: true,
          message: '请选择企业层级',
          trigger: ['change', 'blur'],
        },
      ],
    },
    // {
    //   field: 'Sort',
    //   component: 'InputNumber',
    //   label: '显示顺序：',
    //   colProps: {
    //     span: 8,
    //   },
    //   componentProps: {
    //     style: {
    //       width: '80% !important',
    //     },
    //     // min: 0,
    //   },
    // },
  ];
  const { createMessage } = useMessage();
  const { t } = useI18n();
  //  { validateFields, setFieldsValue, resetFields, clearValidate }
  const [
    registerForm,
    { validateFields, setFieldsValue, resetFields, clearValidate, updateSchema },
  ] = useForm({
    labelWidth: 100,
    layout: 'vertical',
    schemas: schemas,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
  });

  function getTree() {
    const tree = unref(treeRef);
    if (!tree) {
      throw new Error('tree is null!');
    }
    return tree;
  }
  // 展开 折叠
  function expandAll(checkAll) {
    getTree().expandAll(checkAll);
  }
  // 树状图选中事件
  async function handleTreeSelect(_e, info) {
    try {
      loading.value = true;
      let res = await getenterprise([info?.node?.Key]);

      let setValue = {
        Name: res.Name,
        Code: res.Code,
        Level: res.Level.toString(),
      };
      if (res.ParentId) {
        parentInfo.Id = res.ParentId;
        parentInfo.Name = res.ParentName;
        setValue.ParentName = res.ParentName;
      } else {
        setValue.ParentName = '';
      }
      let options = defaultOptions.filter((item) => {
        let val = cloneDeep(item.value);
        return Number(val) >= res.Level;
      });
      updateSchema({
        field: 'Level',
        componentProps: {
          options,
        },
      });
      currentInfo = res;
      setFieldsValue(setValue);
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }
  // 新增父级
  function handleAddFather() {
    // 初始化表单
    resetFields();
    clearValidate();
    currentInfo = {};
    parentInfo = {};
    // 初始化选项
    updateSchema({
      field: 'Level',
      componentProps: {
        options: defaultOptions,
      },
    });
  }
  // 新增子级
  function handleAddChild() {
    if (!currentInfo.Id) {
      createMessage.warning('请选择要创建子级的企业模型！');
      return false;
    }
    parentInfo = currentInfo;
    currentInfo = {};
    // 初始化表单
    resetFields();
    clearValidate();
    let options = defaultOptions.filter((item) => {
      let val = cloneDeep(item.value);
      return Number(val) > parentInfo.Level;
    });
    setFieldsValue({ ParentName: parentInfo.Name });
    // 初始化选项
    updateSchema({
      field: 'Level',
      componentProps: {
        options: options,
      },
    });
  }
  // 保存
  async function handleSave() {
    try {
      loading.value = true;
      let res = await validateFields();
      res.Level = Number(res.Level);
      if (currentInfo.Id) {
        await updateenterprise([{ ...res, Id: currentInfo.Id, ParentId: parentInfo.Id }]);
      } else {
        await addenterprise([{ ...res, ParentId: parentInfo.Id }]);
      }
      initData();
      createMessage.success(t('layout.setting.operatingTitle'));
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }
  //删除
  async function handleDel() {
    if (!currentInfo.Id) {
      createMessage.warning('请选择要删除企业模型！');
      return false;
    }
    try {
      loading.value = true;
      await delenterprise([currentInfo]);
      handleAddFather();
      searchDriver.value = '';
      initData();
      createMessage.success(t('layout.setting.operatingTitle'));
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }
  // 搜索设备
  function onSearchDriver() {
    initData();
  }
  async function initData(isOpenTree = false) {
    try {
      loading.value = true;
      let resByTree = await getenterprisetree(searchDriver.value ? [false,searchDriver.value] : [false,null]);
      treeDataPro.value = resByTree || [];
      if (isOpenTree) {
        nextTick(() => {
          getTree().expandAll(true);
        });
      }

      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }
  onMounted(async () => {
    initData(true);
  });
</script>

<style scoped lang="less">
  .p-4-tag {
    width: 100%;
    height: 100%;
    padding: 0px !important;
  }

  .tag {
    position: relative;
    overflow: hidden;
    height: 100%;
    background-color: #fff;

    .main-head {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      height: 40px;
      background-color: #fff;
      display: flex;
      align-items: center;
      border-bottom: 1px solid #ccc;

      .margin5 {
        margin: 0 5px;
      }
    }

    .main-nav {
      position: absolute;
      top: 40px;
      left: 0;
      bottom: 0;
      width: 240px;
      height: calc(100% - 40px);
      padding: 8px;
      box-sizing: border-box;
      overflow: auto;
      border-right: 1px solid #ccc;

      .btns {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 10px;

        .btns-item {
          flex: 1;
        }

        .btns-item:first-child {
          margin-right: 10px;
        }
      }
    }

    .main-content {
      position: relative;
      height: calc(100% - 40px);
      margin-top: 40px;
      margin-left: 260px;
      overflow: hidden;

      .pagination-box {
        z-index: 9;
        padding: 10px 5px;
        box-sizing: border-box;
        position: absolute;
        width: 100%;
        bottom: 0;
        left: 0;
        right: 0;
        background-color: #fff;
      }
    }

    .main-content::after {
      content: '';
      display: block;
      width: 100%;
      height: 45px;
    }
  }
</style>
